import {BaseService} from 'egg-cool-service';
import * as md5 from 'md5';
import * as _ from 'lodash';
// import { createHash } from 'crypto';
// const request = require('request');
// const crypto = require('crypto');
// const qs = require('qs');

interface QueryParams {
    ShipperCode : string;
    LogisticCode : string;
    OrderCode : string;
}

const KdRequestType = {
    actualTime : '1002' ,
    companyDistinguish : '2002' ,
};

/**
 * 快递
 */
export default class Kuaidi extends BaseService {
    async info (param : QueryParams) {
        // HTKY
        // let {ShipperCode  = '', LogisticCode, OrderCode = ''} = param
        let headers = {//自定义header
            "accept" : "*/*" ,
            "connection" : "Keep-Alive" ,
            "content-type" : "application/x-www-form-urlencoded;charset=utf-8"
        };
        let companyResult : any = await this.ctx.curl (this.app.config.kuaidiniao.companyDistinguishUrl ,
                {
                    // dataType: 'json',
                    method : "POST" ,
                    headers ,
                    data : this.generateFromData (param , KdRequestType.companyDistinguish) ,
                    dataAsQueryString : true
                }
        );

        if ( _.isEmpty (companyResult) ) {
            throw new Error ('获取快递公司为空');
        }
        companyResult = this.bufferToJson (companyResult.res.data);
        if ( _.isEmpty (companyResult.Shippers) ) {
            throw new Error ('获取快递公司失败~');
        }
        if ( this.app.config.kuaidiniao.debug ) {
            console.log ('==========返回快递公司数据==========');
            console.log (companyResult);
        }
        param.ShipperCode = companyResult.Shippers[0].ShipperCode;
        param.OrderCode = '';
        let kdResult : any = await this.ctx.curl (this.app.config.kuaidiniao.actualTimeUrl , {
                    // dataType: 'json',
                    method : "POST" ,
                    headers ,
                    data : this.generateFromData (param , KdRequestType.actualTime) ,
                    dataAsQueryString : true
                }
        );
        console.log ('请求数据' , this.generateFromData (param , KdRequestType.actualTime));
        if ( _.isEmpty (kdResult) ) {
            throw new Error ('获取快递信息失败');
        }
        let result = this.bufferToJson (kdResult.res.data);
        result.ShipperName = companyResult.Shippers[0].ShipperName;
        if ( this.app.config.kuaidiniao.debug ) {
            console.log ('==========返回快递信息数据==========');
            console.log (result);
        }
        if ( result.Success == false || result.Success == 'false' || result.Traces.length == 0 ) {
            throw new Error (result.Reason);
        }
        return result;

    }

    bufferToJson (d) {
        let jsstr = JSON.stringify (d);
        let jsondata = JSON.parse (jsstr);
        let buf = Buffer.from (jsondata);
        let data = buf.toString ();
        let sx = JSON.parse (data);
        return sx;
    }

    generateFromData (params , type) {
        const requestData = this.generateRequestData (params);
        const formData = {
            RequestData : encodeURI (requestData) ,
            // RequestData:requestData,
            EBusinessID : this.app.config.kuaidiniao.id ,
            RequestType : type ,
            DataSign : this.generateDataSign (requestData) ,
            DataType : '2'
        };
        return formData;
    }

    generateRequestData (params) {
        return JSON.stringify (params);
    }

    generateDataSign (requestData : any) {
        return encodeURI (Buffer.from (md5 (requestData + this.app.config.kuaidiniao.key)).toString ('base64'));
    }

}
